# -*- coding: utf-8 -*-

import logging
import traceback

from werkzeug.utils import redirect

from odoo.http import request

from odoo_contrib import http as contrib_http
from odoo_contrib.parser import parse_with
from odoo_contrib.marshal import marshal_with

from ...schemas import parsers
from ...schemas import marshals

from ...adaptor.factory import WechatMPFactory

from ...utils.auth import Auth

logger = logging.getLogger(__name__)


@contrib_http.route('/wechat/mp/oauth')
class WechatMPMenu(contrib_http.Controller):
    @contrib_http.route(['/login', '/login/<site>'], methods=['GET'], auth='none', type='http')
    @parse_with(parsers.mp.OAuthParser)
    def oauth(self, **kwargs):
        site = kwargs.get('site')
        auth = Auth()
        payload = self.parser.parse()
        params = {
            'code': payload['code'],
            'site': site,
        }
        user, token = auth.login(**params)
        request.session.auth_token = token
        mpapp = WechatMPFactory()[site]
        redirect_url = mpapp.retrieve_post_oauth_redirect_url(payload.get('state'))
        return redirect(redirect_url)

    @contrib_http.route(['/locator', '/locator/<site>'], methods=['GET'], auth='none', type='http')
    def locator(self, **kwargs):
        site = kwargs.get('site')
        mpapp = WechatMPFactory()[site]
        redirect_url = mpapp.generate_oauth_redirect_url(request.httprequest.referrer)
        return redirect(redirect_url)
